import axios,{AxiosError,AxiosRequestConfig} from 'axios'
import store from '@/store'
// import router from '@/router'
import {ElNotification} from 'element-plus'
// 创建 axios 实例
const request = axios.create({
    // API 请求的默认前缀
    // baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 60000 // 请求超时时间
  })
  // 异常拦截处理器
const errorHandler = async (error:AxiosError) => {
    if (error.response) {
      const data = error.response.data
      // 从 localstorage 获取 token
      const token = localStorage.getItem('token')
      if (error.response.status === 403) {
        ElNotification.error({
          title: 'Forbidden',
          message: data.msg
        })
        if (token) {
          store.dispatch('Logout').then(() => {
            window.location.reload()
          })
        }
        // await store.dispatch('Logout')
        // router.push({ name: 'login' })
      }
      if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
        ElNotification.error({
            title: 'Unauthorized',
            message: 'Authorization verification failed'
        })
        if (token) {
          store.dispatch('Logout').then(() => {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          })
        }
      }
      ElNotification.error({
        title: error.message,
        message: data.message
      })
    }
  
    return Promise.reject(error)
  }
  
  // request interceptor
  request.interceptors.request.use((config:AxiosRequestConfig) => {
    const token = localStorage.getItem('token')
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (token&&config.headers) {
      config.headers.Authorization = token
    }
    return config
  }, errorHandler)

  // response interceptor
request.interceptors.response.use(response => {
    const { token } = response.headers
    if (token) {
      localStorage.setItem('token', token)
      store.commit('SET_TOKEN', token)
    }


    return response.data as any
  }, errorHandler)

  export default request